document.addEventListener('DOMContentLoaded', function() {
    // 表单元素
    const registerForm = document.getElementById('registerForm');
    const usernameInput = document.getElementById('username');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    const verificationCodeInput = document.getElementById('verificationCode');
    const agreeTermsCheckbox = document.getElementById('agreeTerms');
    const sendCodeBtn = document.getElementById('sendCode');
    
    // 错误提示元素
    const usernameError = document.getElementById('usernameError');
    const emailError = document.getElementById('emailError');
    const passwordError = document.getElementById('passwordError');
    const confirmPasswordError = document.getElementById('confirmPasswordError');
    const verificationCodeError = document.getElementById('verificationCodeError');
    const termsError = document.getElementById('termsError');
    
    // 密码强度指示器
    const strengthBar = document.getElementById('strengthBar');
    const strengthText = document.getElementById('strengthText');
    
    // 显示/隐藏密码
    const togglePassword = document.getElementById('togglePassword');
    const toggleConfirmPassword = document.getElementById('toggleConfirmPassword');
    
    togglePassword.addEventListener('click', function() {
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        this.innerHTML = type === 'password' ? '<i class="fas fa-eye"></i>' : '<i class="fas fa-eye-slash"></i>';
    });
    
    toggleConfirmPassword.addEventListener('click', function() {
        const type = confirmPasswordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        confirmPasswordInput.setAttribute('type', type);
        this.innerHTML = type === 'password' ? '<i class="fas fa-eye"></i>' : '<i class="fas fa-eye-slash"></i>';
    });
    
    // 用户名实时验证
    usernameInput.addEventListener('input', function() {
        validateUsername();
    });
    
    // 邮箱实时验证
    emailInput.addEventListener('input', function() {
        validateEmail();
    });
    
    // 密码实时验证和强度检测
    passwordInput.addEventListener('input', function() {
        validatePassword();
        checkPasswordStrength();
    });
    
    // 确认密码实时验证
    confirmPasswordInput.addEventListener('input', function() {
        validateConfirmPassword();
    });
    
    // 验证码发送按钮
    sendCodeBtn.addEventListener('click', function() {
        sendVerificationCode();
    });
    
    // 表单提交验证
    registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 验证所有字段
        const isUsernameValid = validateUsername();
        const isEmailValid = validateEmail();
        const isPasswordValid = validatePassword();
        const isConfirmPasswordValid = validateConfirmPassword();
        const isVerificationCodeValid = validateVerificationCode();
        const isTermsAgreed = validateTerms();
        
        if (isUsernameValid && isEmailValid && isPasswordValid && 
            isConfirmPasswordValid && isVerificationCodeValid && isTermsAgreed) {
            // 所有验证通过，提交表单
            submitRegistration();
        }
    });
    
    // 验证用户名
    function validateUsername() {
        const username = usernameInput.value.trim();
        const usernameRegex = /^[a-zA-Z0-9]{4,16}$/;
        
        if (username === '') {
            showError(usernameError, '请输入用户名');
            return false;
        } else if (!usernameRegex.test(username)) {
            showError(usernameError, '用户名必须为4-16位字母或数字');
            return false;
        } else {
            hideError(usernameError);
            return true;
        }
    }
    
    // 验证邮箱
    function validateEmail() {
        const email = emailInput.value.trim();
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        
        if (email === '') {
            showError(emailError, '请输入邮箱地址');
            return false;
        } else if (!emailRegex.test(email)) {
            showError(emailError, '请输入有效的邮箱地址');
            return false;
        } else {
            hideError(emailError);
            return true;
        }
    }
    
    // 验证密码
    function validatePassword() {
        const password = passwordInput.value;
        
        if (password === '') {
            showError(passwordError, '请输入密码');
            return false;
        } else if (password.length < 8) {
            showError(passwordError, '密码长度不能少于8位');
            return false;
        } else {
            hideError(passwordError);
            return true;
        }
    }
    
    // 验证确认密码
    function validateConfirmPassword() {
        const password = passwordInput.value;
        const confirmPassword = confirmPasswordInput.value;
        
        if (confirmPassword === '') {
            showError(confirmPasswordError, '请再次输入密码');
            return false;
        } else if (password !== confirmPassword) {
            showError(confirmPasswordError, '两次输入的密码不一致');
            return false;
        } else {
            hideError(confirmPasswordError);
            return true;
        }
    }
    
    // 验证验证码
    function validateVerificationCode() {
        const code = verificationCodeInput.value.trim();
        
        if (code === '') {
            showError(verificationCodeError, '请输入验证码');
            return false;
        } else if (code.length !== 6) {
            showError(verificationCodeError, '验证码必须为6位数字');
            return false;
        } else {
            hideError(verificationCodeError);
            return true;
        }
    }
    
    // 验证条款同意
    function validateTerms() {
        if (!agreeTermsCheckbox.checked) {
            showError(termsError, '请阅读并同意用户协议和隐私政策');
            return false;
        } else {
            hideError(termsError);
            return true;
        }
    }
    
    // 检查密码强度
    function checkPasswordStrength() {
        const password = passwordInput.value;
        let strength = 0;
        
        // 长度加分
        if (password.length >= 8) strength += 1;
        if (password.length >= 12) strength += 1;
        
        // 包含小写字母
        if (/[a-z]/.test(password)) strength += 1;
        
        // 包含大写字母
        if (/[A-Z]/.test(password)) strength += 1;
        
        // 包含数字
        if (/\d/.test(password)) strength += 1;
        
        // 包含特殊字符
        if (/[^a-zA-Z0-9]/.test(password)) strength += 1;
        
        // 更新UI
        const strengthPercent = (strength / 6) * 100;
        const strengthBarElement = strengthBar.querySelector('::after');
        
        strengthBar.style.setProperty('--strength-width', `${strengthPercent}%`);
        
        if (strength <= 2) {
            strengthBar.style.setProperty('--strength-color', '#ff4757');
            strengthText.textContent = '密码强度: 弱';
        } else if (strength <= 4) {
            strengthBar.style.setProperty('--strength-color', '#ffa502');
            strengthText.textContent = '密码强度: 中等';
        } else {
            strengthBar.style.setProperty('--strength-color', '#2ed573');
            strengthText.textContent = '密码强度: 强';
        }
    }
    
    // 发送验证码
    function sendVerificationCode() {
        // 先验证邮箱
        if (!validateEmail()) return;
        
        // 禁用按钮并开始倒计时
        let countdown = 60;
        sendCodeBtn.disabled = true;
        sendCodeBtn.textContent = `${countdown}秒后重新发送`;
        
        const timer = setInterval(() => {
            countdown--;
            sendCodeBtn.textContent = `${countdown}秒后重新发送`;
            
            if (countdown <= 0) {
                clearInterval(timer);
                sendCodeBtn.disabled = false;
                sendCodeBtn.textContent = '获取验证码';
            }
        }, 1000);
        
        // 模拟发送验证码到邮箱
        // 实际应用中这里应该调用API发送验证码
        alert(`验证码已发送至: ${emailInput.value.trim()}\n(演示用途，实际应用中会发送真实验证码)`);
    }
    
    // 提交注册
    function submitRegistration() {
        const registerBtn = document.querySelector('.btn-register');
        const originalText = registerBtn.innerHTML;
        registerBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 注册中...';
        registerBtn.disabled = true;
        
        // 收集用户数据
        const userData = {
            username: usernameInput.value.trim(),
            email: emailInput.value.trim(),
            password: passwordInput.value // 注意：实际应用中密码应该加密存储
        };
        
        // 保存用户数据到localStorage
        let users = JSON.parse(localStorage.getItem('users')) || [];
        users.push(userData);
        localStorage.setItem('users', JSON.stringify(users));
        
        // 模拟API请求延迟
        setTimeout(() => {
            alert('注册成功！即将跳转到登录页面');
            
            // 重置表单
            registerForm.reset();
            registerBtn.innerHTML = originalText;
            registerBtn.disabled = false;
            
            // 跳转到登录页面
            window.location.href = 'login.html';
        }, 1000);
    }
    
    // 显示错误信息
    function showError(element, message) {
        element.textContent = message;
        element.style.display = 'block';
    }
    
    // 隐藏错误信息
    function hideError(element) {
        element.textContent = '';
        element.style.display = 'none';
    }
});